package fitness

import (
	"fitness/internal/controller/fitness/bo"
	"fitness/internal/dao/fitness"
	fitnessEntity "fitness/internal/entity/fitness"
	"fitness/pkg/utils/R"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

type DetailService struct {
	DetailDao *fitness.DetailDao
	Log       *zap.Logger
}

func NewDetailService(DetailDao *fitness.DetailDao,
	Log *zap.Logger) *DetailService {
	return &DetailService{
		DetailDao: DetailDao,
		Log:       Log,
	}
}

func (s *DetailService) GetDetails(c *gin.Context) {
	var detailQuery bo.DetailQuery
	err := c.ShouldBindJSON(&detailQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}

	list, err := s.DetailDao.QueryDetailList(detailQuery.FitnessDate, nil)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(list))
}

func (s *DetailService) Insert(c *gin.Context) {
	var detailQuery fitnessEntity.Detail
	err := c.ShouldBindJSON(&detailQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}

	list, err := s.DetailDao.Insert(detailQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(list))
}

func (s *DetailService) Update(c *gin.Context) {
	var detailQuery fitnessEntity.Detail
	err := c.ShouldBindJSON(&detailQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}

	list, err := s.DetailDao.Update(detailQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(list))
}

func (s *DetailService) Delete(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
	}

	err = s.DetailDao.DeleteById(id)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(nil))
}

func (s *DetailService) Courses(c *gin.Context) {
	yearStr := c.Query("year")
	monthStr := c.Query("month")
	// 2. 转换为整数（确保参数有效）
	year, err1 := strconv.Atoi(yearStr)
	month, err2 := strconv.Atoi(monthStr)
	if err1 != nil || err2 != nil || month < 1 || month > 12 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的年月参数"})
		return
	}

	// 3. 计算当月起止日期（整数类型：20250701、20250731）
	startDate := year*10000 + month*100 + 1 // 2025*10000 + 7*100 + 1 = 20250701
	endDate := year*10000 + month*100 + 31
	m, err := s.DetailDao.Courses(startDate, endDate)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(m))
}
